import React, {Component} from "react";
import { Card, Image, Upload, Input, Form, message, Button } from 'antd'

import { storeDetails, updateStore,addStore } from '../../api/food'
class RestaurantDetails extends Component {
    restaurant = React.createRef()
    state = {
        id: '',
        info: {
            shopname: '',
            shopAddress: '',
            shopScore: '',
            perCapita: '',
            rpicture: ''
        },
        Look: true
    }
    componentDidMount () {
        const id = this.props.location.query ? this.props.location.query.id :  window.sessionStorage.getItem('id')
        if (id) {
            window.sessionStorage.setItem('id', id)
            const Look = window.sessionStorage.getItem('Look') || true
            this.setState({id, Look}, () => {
             this.getDetails()
         })
        } else {
            this.setState({Look: false})
        }
     }

     componentWillUnmount () {
        window.sessionStorage.setItem('id', '')
        window.sessionStorage.setItem('Look', true)
      }

     // 获取美食详情
     getDetails = async () => {
        const res = await storeDetails({rid: this.state.id})
        const info = res.data.restaurant
        this.setState({info})
     }

     // 触发表单校验
     FormSubmit = () => {
        this.restaurant.current.submit()
     }
    
     // 表单数据校验成功
     successData = (values) => {
         console.log(values)
        this.setState({info:{ ...this.state.info, ...values}}, () => {
            this.confrim()
           })
     }

     // 表单检验失败
     FormError = () => {
         message.error('数据错误，操作失败')
     }

     // 图片上传成功
     handleChange = (info) => {
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
            const rpicture = info.file.response.data.url
           this.setState({info: {...this.state.info, rpicture}})
          message.success('图片上传成功');
        } else if (info.file.status === 'error') {
          message.error('图片上传失败');
        }
      
      }

      // 更新数据
      updateData = async () => {
          console.log(this.state.info)
          const res = await updateStore(this.state.info)
          if (res.code === 200) {
            message.success('更新数据成功')
            this.getDetails()
            this.setState({Look: true})
        } else {
         message.error('更新数据失败')
        }
      }

      // 增加数据
      addData = async () => {
        const res = await addStore(this.state.info)
       if (res.code === 200) {
           message.success('更新数据成功')
           this.setState({Look: true})
           this.back()
       } else {
        message.error('更新数据失败')
       }
      
      }

      // 返回上一级
      back = () => {
          this.props.history.goBack()
      }

      // 编辑
      Edit = () => {
        this.setState({Look: false, fpicture: this.state.fpicture})
        window.sessionStorage.setItem('Look', false)
      }

      // 返回编辑
      backLook = () => {
          if (this.state.id) {
            this.setState({Look: true})
            window.sessionStorage.setItem('Look', true)
          } else {
              this.back()
              this.setState({Look: true})
              window.sessionStorage.setItem('Look', true)
          }
      
      }

      // 确认
      confrim = () => {
          if (this.state.id) {
              this.updateData()
          } else {
              this.addData()
          } 
      }
      
    

  render() {
    const { info, Look } = this.state
    return (
        <div>
            {/* 编辑 */}
           
          {Look ? ( <Card style={{minHeight: '720px'}}>
              <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <Button type="ghost" onClick={() => this.back()} className="backBtn">返回</Button>
              <Button className="editBtn"  onClick={() => {this.Edit()}}>编辑</Button>
              </div>
            <Form>
                <div style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>餐厅名称:</span>
                   <span className="textHd2">{info.shopname}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px' ,display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>餐厅地址:</span>
                   <span className="textHd2">{info.shopAddress}</span>
               </div>
                </div>
                <div  style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>餐厅评分:</span>
                   <span className="textHd2">{info.shopScore}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>人均消费:</span>
                   <span className="textHd2">{info.perCapita}</span>
               </div>
                </div>
                <div  style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>城市:</span>
                   <span className="textHd2">{info.city}</span>
               </div>
               <div style={{flex: 1,  minHeight: '250px', alignItems: 'center', lineHeight: '72px',alignContent: 'center'}}>
                   <span style={{fontSize: '18px', fontWeight: 'bold'}}>图片:</span>
                  <Image className="avater"  preview={false} src={info.rpicture} fallback=""></Image >
               </div>
                </div>
            </Form>
            </Card>) : (
               <Card style={{minHeight: '720px'}}>
                <Form 
                ref={this.restaurant}
                initialValues={info} 
                onFinish={this.successData}
                onFinishFailed={this.FormError}>
                    <div style={{display: 'flex'}}>
                    <Form.Item label="餐厅名称"    style={{flex: 1}} rules={[{required: true,}]} name="shopname">
                       <Input style={{width: '320px'}} ></Input>
                   </Form.Item>
                   <Form.Item   label="餐厅地址"   style={{flex: 1}} rules={[{required: true,}]} name="shopAddress">
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}}>
                    <Form.Item  label="餐厅评分"  style={{flex: 1}} rules={[{required: true,}]} name="shopScore">
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                   <Form.Item   label="人均消费"  style={{flex: 1}}  rules={[{required: true,}]} name="perCapita">
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}}>
                    <Form.Item   label="城市"  style={{flex: 1}}  rules={[{required: true,}]} name="city">
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item> 
                   <Form.Item  label="图片" style={{flex: 1}}>
                      <Form.Item>
                      <Upload  action="http://111.75.252.147:8888/app/scenic/picUpload" name="file" onChange={(info) => this.handleChange(info)}  >
                            <Image className="avater"  preview={false} src={info.rpicture} fallback=""></Image >
                      </Upload> 
                      </Form.Item>
                   </Form.Item>
                    </div>
                </Form>
                <div style={{display: 'flex', justifyContent: 'flex-end'}}>
             <Button className="editBtn"  onClick={() => {this.FormSubmit()}}>确认</Button>
              <Button type="ghost" onClick={() => this.backLook()} className="backBtn" style={{marginLeft: '32px'}}>取消</Button>
              </div>
                </Card>
          )}
            
            {/* 查看 */}
        </div>
    );
  }
}

export default RestaurantDetails;